/*右键菜单
 * @Author: kevin.huang 
 * @Date: 2018-07-21 13:24:37 
 * @Last Modified by: kevin.huang
 * @Last Modified time: 2019-02-12 23:51:21
 * Copyright (c): kevin.huang Released under MIT License
 *  opts=[{
		text: '刷新当前页面',
	    iconCls: 'reload',
	    click: fn() 点击事件
	}]
 */
(function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['$B'], function (_$B) {
            return factory(global, _$B);
        });
    } else {
        if(!global["$B"]){
            global["$B"] = {};
        }
        factory(global, global["$B"]);
    }
}(typeof window !== "undefined" ? window : this, function (window, $B) {
    var document = window.document;
    var $body;
    function _getBody(){
        if(!$body){
            $body = $(document.body).css("position", "relative");
        }
        return $body;        
    }
    /***全局关闭***/
    var hasIns = false;   
    var shouldClosed = true;
    window["_ctxmenu_close_fn"] = function(){
        if(hasIns && shouldClosed){
            var moreWraps = _getBody().children(".k_context_menu_container");      
            moreWraps.hide();
        }        
    };     
    $(window).on('mouseup._ctxmenu_close_fn', function () { 
        if(hasIns){
            window["_ctxmenu_close_fn"]();
        }        
        setTimeout(function() {            
            if(window.parent !== window.self && window.parent["_ctxmenu_close_fn"]){              
                window.parent["_ctxmenu_close_fn"]();
            }
        }, 10);
    });     
    function Ctxmenu(jqObj, opts) {
        hasIns = true;
        $B.extend(this, Ctxmenu);
        this.$body = _getBody();
        var _this = this;
        this.$body.css('position', 'relative').on('click._k_c_menu', function (e) {
            _this.$body.children(".k_context_menu_container").remove();
            return false;
        });
        if (arguments.length === 1) {
            this.jqObj = this.$body;
            this.opts = arguments[0];
        } else {
            this.jqObj = jqObj;
            this.opts = opts;
        }
        this.opts.push({
            text: $B.config.closeLable,
            iconCls: 'fa-minus',
            click: function () {
                _this.$body.children(".k_context_menu_container").remove();
            }
        });
        function _destorySubmenu($cwrap) {
            var submenu = $cwrap.data("submenu");
            if (submenu) {
                submenu.remove();
                $cwrap.removeData("submenu");
            }
        }
        var createItem = function (opt, $wrap) {
            var $it = $('<div class="k_context_menu_item_cls"><span class="k_context_menu_item_ioc"><i class="k_ctxmenu_i fa ' + opt.iconCls + '"></i></span><span class="k_context_menu_item_txt">' + opt.text + '</span></div>').appendTo($wrap).on({
                click: function () {
                    var _$t = $(this);
                    _$t.parent().remove();
                    if (opt.click) {
                        setTimeout(function () {
                            opt.click.call(_$t);
                        }, 10);
                    }
                }
            });
            if (opt.items) {
                $it.append('<span class="k_context_menu_more_ioc"><i class="fa fa-angle-double-right k_ctxmenu_i"></i></span>');
                $it.mouseenter(function () {
                    var $t = $(this);
                    var _data = $t.data("items");
                    var $cwrap = $wrap.data("submenu");
                    var offset = $t.offset();
                    var left = offset.left + $t.outerWidth() + 3;
                    var top = offset.top;
                    if ($cwrap) {
                        _destorySubmenu($cwrap);
                        $cwrap.children().remove();
                        $cwrap.css({
                            left: left + 'px',
                            top: top + 'px'
                        }).show();
                    } else {
                        $cwrap = $("<div style='position:absolute;z-index:99999999999999999999;height:auto;' class='k_context_menu_container k_box_shadow k_box_radius'/>").appendTo(_this.$body).css({
                            left: left + 'px',
                            top: top + 'px'
                        });
                        $wrap.data("submenu", $cwrap);
                    }
                    for (var i = 0, l = opt.items.length; i < l; ++i) {
                        var _opt = opt.items[i];
                        createItem(_opt, $cwrap);
                    }
                }).data("items", opt.items);
            } else {
                $it.mouseenter(function () {
                    var $t = $(this);
                    var $cwrap = $wrap.data("submenu");
                    if ($cwrap) {
                        $cwrap.hide();
                    }
                });
            }
        };
        this.mousedown = function (e) {
            var left = e.clientX;
            var top = e.clientY;
            _this.$body.children(".k_context_menu_container").remove();
            //2147483647
            var $wrap = $("<div style='position:absolute;z-index:-1000;height:auto;' class='k_context_menu_container k_box_shadow k_box_radius'/>").appendTo(_this.$body).css({
                left: left + 'px',
                top: top + 'px'
            });
            $.each(_this.opts, function () {
                createItem(this, $wrap);
            });
            var width = $wrap.outerWidth();
            var availableWidth = _this.$body.width() - left;
            var diff = availableWidth - width;
            var css = {"z-index":2147483647};
            if(diff < 0){
                css.left = left + diff;               
            }
            $wrap.css(css);
        };
        this.jqObj.on({
            mousedown: function (e) {
                if (3 === e.which) {
                    shouldClosed = false;
                    _this.mousedown(e);
                    setTimeout(function() {
                        shouldClosed = true;
                    },300);
                }
            },mouseup:function(){
                return false;
            }
        });
        _this.$body.on("contextmenu", function (e) {
            return false;
        });
    }
    Ctxmenu.prototype = {
        bandTarget: function (target) {
            var _this = this;
            target.on({
                mousedown: function (e) {
                    if (3 === e.which) {
                        shouldClosed = false;
                        _this.mousedown(e);
                        setTimeout(function() {
                            shouldClosed = true;
                        },300);
                    }
                },
                contextmenu: function (e) {
                    return false;
                }
            });
        },
        hide: function () {
            this.$body.children(".k_context_menu_container").remove();
        }
    };
    $B["Ctxmenu"] = Ctxmenu;
    return Ctxmenu;
}));